package rpc_netty.Serializer;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rpc_1.object.RpcRequest;
import rpc_netty.interfaces.CommonSerializer;

import java.io.IOException;

public class JsonSerializer implements CommonSerializer {
    private static final Logger logger= LoggerFactory.getLogger(JsonSerializer.class);
    private ObjectMapper objectMapper=new ObjectMapper();
    @Override
    public byte[] serialize(Object object) {
        try{
            return objectMapper.writeValueAsBytes(object);
        } catch (JsonProcessingException e) {
            logger.error("error when serializing,{}",e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Object deserialize(byte[] bytes, Class<?> clazz)  {
        try {
            Object obj=objectMapper.readValue(bytes,clazz);
            if (obj instanceof RpcRequest)
                obj=handleRequest(obj);
            return obj;
        } catch (IOException e) {
            logger.error("error when deserializing",e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    private Object handleRequest(Object object) throws IOException {
        RpcRequest rpcRequest=(RpcRequest)object;
        for (int i=0;i<rpcRequest.getParamTypes().length;i++){
            Class<?> clazz = rpcRequest.getParamTypes()[i];
            if (!clazz.isAssignableFrom(rpcRequest.getParameters()[i].getClass())){
                byte[] bytes = objectMapper.writeValueAsBytes(rpcRequest.getParameters()[i]);
                rpcRequest.getParameters()[i]=objectMapper.readValue(bytes,clazz);
            }
        }
        return rpcRequest;
    }

    @Override
    public int getCode() {
        return SerializerCode.valueOf("Json").getCode();
    }
}
